from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.dao.kq_attendance_dao import Kq_attendanceDao
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.kq_attendance_vo import Kq_attendancePageQueryModel, Kq_attendanceModel, \
    DeleteKq_attendanceModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class Kq_attendanceService:
    """
    考勤数据表模块服务层
    """

    @classmethod
    async def get_kq_attendance_list_services(
        cls, query_db: AsyncSession, query_object: Kq_attendancePageQueryModel, is_page: bool = False
    ):
        """
        获取考勤数据表列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 考勤数据表列表信息对象
        """
        kq_attendance_list_result = await Kq_attendanceDao.get_kq_attendance_list(query_db, query_object, is_page)

        return kq_attendance_list_result


    @classmethod
    async def add_kq_attendance_services(cls, query_db: AsyncSession, page_object: Kq_attendanceModel):
        """
        新增考勤数据表信息service

        :param query_db: orm对象
        :param page_object: 新增考勤数据表对象
        :return: 新增考勤数据表校验结果
        """
        try:
            await Kq_attendanceDao.add_kq_attendance_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_kq_attendance_services(cls, query_db: AsyncSession, page_object: Kq_attendanceModel):
        """
        编辑考勤数据表信息service

        :param query_db: orm对象
        :param page_object: 编辑考勤数据表对象
        :return: 编辑考勤数据表校验结果
        """
        edit_kq_attendance = page_object.model_dump(exclude_unset=True, exclude={'del_flag', 'create_by', 'create_time', })
        kq_attendance_info = await cls.kq_attendance_detail_services(query_db, page_object.id)
        if kq_attendance_info.id:
            try:
                await Kq_attendanceDao.edit_kq_attendance_dao(query_db, edit_kq_attendance)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='考勤数据表不存在')

    @classmethod
    async def delete_kq_attendance_services(cls, query_db: AsyncSession, page_object: DeleteKq_attendanceModel):
        """
        删除考勤数据表信息service

        :param query_db: orm对象
        :param page_object: 删除考勤数据表对象
        :return: 删除考勤数据表校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await Kq_attendanceDao.delete_kq_attendance_dao(query_db, Kq_attendanceModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入序号为空')

    @classmethod
    async def kq_attendance_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取考勤数据表详细信息service

        :param query_db: orm对象
        :param id: 序号
        :return: 序号对应的信息
        """
        kq_attendance = await Kq_attendanceDao.get_kq_attendance_detail_by_id(query_db, id=id)
        if kq_attendance:
            result = Kq_attendanceModel(**CamelCaseUtil.transform_result(kq_attendance))
        else:
            result = Kq_attendanceModel(**dict())

        return result

    @staticmethod
    async def export_kq_attendance_list_services(kq_attendance_list: List):
        """
        导出考勤数据表信息service

        :param kq_attendance_list: 考勤数据表信息列表
        :return: 考勤数据表信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '序号',
            'userId': '用户编号',
            'userName': '用户姓名',
            'amPm': '考勤时段',
            'khWork': '考勤类型',
            'punchDate': '打卡日期',
            'punchTime': '打卡时间',
            'punchResult': '考勤结果',
            # 'delFlag': '删除标志',
            # 'createBy': '创建者',
            # 'createTime': '创建时间',
            # 'updateBy': '更新者',
            # 'updateTime': '更新时间',
            # 'remark': '备注',
        }
        binary_data = ExcelUtil.export_list2excel(kq_attendance_list, mapping_dict)

        return binary_data
